package org.jeecg.modules.iot.mqtt.server.service;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;



public class TencentLocationService {

    // 腾讯位置服务的 API URL
    private static final String API_URL = "https://apis.map.qq.com/ws/location/v1/network";

    // 腾讯位置服务的 API Key（请替换为您自己的 Key）
    private static final String API_KEY =  "TO4BZ-B73WZ-W52XS-TWOZL-YZD3E-JQBTG";

    /**
     * 根据设备和位置信息获取定位结果
     * @param deviceId 设备唯一标识
     * @param gpsInfo GPS 信息（JSON 格式）
     * @param cellInfo 基站信息（JSON 数组）
     * @param wifiInfo Wi-Fi 信息（JSON 数组）
     * @param beaconInfo 蓝牙信息（JSON 数组）
     * @param getPoi 是否获取周边 POI 信息
     * @return 定位结果的 JSON 数据
     * @throws Exception 如果请求失败抛出异常
     */
    public static String getLocation(String deviceId, JSONObject gpsInfo, JSONObject[] cellInfo, JSONObject[] wifiInfo, JSONObject[] beaconInfo, int getPoi) throws Exception {
        // 构建请求的 JSON 数据
        JSONObject requestData = new JSONObject();
        requestData.put("key", API_KEY);
        requestData.put("device_id", deviceId);
        requestData.put("get_poi", getPoi);

        if (gpsInfo != null) {
            requestData.put("gpsinfo", gpsInfo);
        }

        if (cellInfo != null) {
            requestData.put("cellinfo", cellInfo);
        }

        if (wifiInfo != null) {
            requestData.put("wifiinfo", wifiInfo);
        }

        if (beaconInfo != null) {
            requestData.put("beaconinfo", beaconInfo);
        }

        // 将请求发送到 API
        String jsonResponse = sendPostRequest(API_URL, requestData.toString());

        // 返回响应内容
        return jsonResponse;
    }

    /**
     * 发送 POST 请求
     * @param urlString 请求的 URL
     * @param jsonInputString 请求的 JSON 数据
     * @return 响应的字符串（JSON 格式）
     * @throws Exception 如果请求失败抛出异常
     */
    private static String sendPostRequest(String urlString, String jsonInputString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        // 发送请求数据
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        }

        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
        }

        conn.disconnect();
        return response.toString();
    }

    /**
     * 示例调用方法
     */
    public static void main(String[] args) {
        try {
            // 准备 GPS 信息
            JSONObject gpsInfo = new JSONObject();
           /* gpsInfo.put("latitude", 29.055488);
            gpsInfo.put("longitude", 119.472340);
            gpsInfo.put("altitude", 100);
            gpsInfo.put("accuracy", 150);
            gpsInfo.put("bearing", 90);
            gpsInfo.put("speed", 5.5);
            gpsInfo.put("viewstar", 9);
            gpsInfo.put("usedstar", 6);*/

            // 准备基站信息
            JSONObject cell1 = new JSONObject();
            cell1.put("mcc", 460);
            cell1.put("mnc", 0);
            cell1.put("lac", 22418);
            cell1.put("cellid", 104549635);
            cell1.put("rss", 51);

            JSONObject cell2 = new JSONObject();
            cell2.put("mcc", 460);
            cell2.put("mnc", 0);
            cell2.put("lac",  22418);
            cell2.put("cellid", 104549664);
            cell2.put("rss", 43);

            JSONObject[] cellInfo = { cell1, cell2 };

            // 准备 Wi-Fi 信息
            JSONObject wifi1 = new JSONObject();
            wifi1.put("mac", "78a106a5b166");
            wifi1.put("rssi", -81);

            JSONObject wifi2 = new JSONObject();
            wifi2.put("mac", "608f5c66b3f7");
            wifi2.put("rssi", -82);

            JSONObject[] wifiInfo = { wifi1, wifi2 };

           /* // 准备蓝牙信息
            JSONObject beacon1 = new JSONObject();
            beacon1.put("mac", "19:18:FC:01:DB:F4");
            beacon1.put("major", 10078);
            beacon1.put("minor", 30859);
            beacon1.put("rssi", -98);
            beacon1.put("time", 1532068218123L);

            JSONObject beacon2 = new JSONObject();
            beacon2.put("mac", "19:18:FC:01:DC:24");
            beacon2.put("major", 10078);
            beacon2.put("minor", 30907);
            beacon2.put("rssi", -92);
            beacon2.put("time", 1532068221123L);*/

            /*JSONObject[] beaconInfo = { beacon1, beacon2 };*/
            JSONObject[] beaconInfo = null;

            // 请求定位结果
            String jsonResponse = getLocation("869896021034807", gpsInfo, cellInfo, wifiInfo, beaconInfo, 1);

            // 打印响应（JSON 格式）
            System.out.println("Response: " + jsonResponse);

            // 解析响应
            JSONObject responseObj = JSONObject.parseObject(jsonResponse);
            if (responseObj.getInteger("status") == 0) {
                JSONObject result = responseObj.getJSONObject("result");
                System.out.println("Address: " + result.getString("address"));
                System.out.println("Latitude: " + result.getJSONObject("location").getDouble("latitude"));
                System.out.println("Longitude: " + result.getJSONObject("location").getDouble("longitude"));
            } else {
                System.out.println("Error: " + responseObj.getString("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}